<template>
  <div>
    <div class="harden-tabs">
      <div class="harden-tabs-nav" ref="container">
        <div
          class="harden-tabs-nav-item"
          @click="select(e)"
          :class="{ selected: e === selected }"
          v-for="(e, index) in titles"
          :ref="el => {if (e===selected) selectedItem = el}"
          :key="index"
        >
          {{ e }}
        </div>
        <div class="harden-tabs-nav-line" ref="indicator"></div>
      </div>
      <div class="harden-tabs-content">
        <component
          class="harden-tabs-content-item"
          :is="current"
          :key="current.props.title"
        />
      </div>
    </div>
  </div>
</template>
<script lang="ts">
import { computed, onMounted, ref , watchEffect} from "vue";
import Tab from "./Tab.vue";
export default {
  props: {
    selected: {
      type: String,
    },
  },
  setup(porps, context) {
    const selectedItem = ref<HTMLDivElement>([]);
    const indicator = ref<HTMLDivElement>([]);
    const container = ref<HTMLDivElement>([]);
    //检查用户是否用错了标签，并抛出错误
    const defaults = context.slots.default();
    onMounted(() => {
      watchEffect(() => {
        // 计算选中项的宽度
        const {width} = selectedItem.value.getBoundingClientRect()
        indicator.value.style.width = width + 'px'

        //计算选中项横线动画偏移量
        const {
          left: left1
        } = container.value.getBoundingClientRect()
        const {
          left: left2
        } = selectedItem.value.getBoundingClientRect()
        const left = left2 - left1
        indicator.value.style.left = left + 'px'
      })
    })
    defaults.forEach((tag) => {
      if (tag.type !== Tab) {
        throw new Error("Tabs 子标签必须是 Tab");
      }
    });
    //拿到title
    const titles = defaults.map((tag) => {
      if (tag.props) {
        return tag.props.title;
      }
    });

    const current = computed(() => {
      return defaults.filter((tag) => {
        return tag.props.title === porps.selected;
      })[0];
    });
    console.log(current, 56666);
    const select = (title: string) => {
      context.emit("update:selected", title);
    };
    return {
      defaults,
      titles,
      current,
      select,
      selectedItem,
      indicator,
      container
    };
  },
};
</script>
<style lang="scss">
$blue: #40a9ff;
$color: #333;
$border-color: #d9d9d9;
.harden-tabs {
  &-nav {
    position: relative;
    display: flex;
    color: $color;
    border-bottom: 1px solid $border-color;
    &-item {
      padding: 8px 0;
      margin: 0 16px;
      cursor: pointer;
      &:first-child {
        margin-left: 0;
      }
      &.selected {
        color: $blue;
      }
    }
    &-line {
      position: absolute;
      bottom: -1px;
      height: 3px;
      background: $blue;
      left: 0;
      width: 100px;transition: all 250ms;
    }
  }
  &-content {
    padding: 8px 0;
  }
}
</style>